<template>
  <li>
    <label>
      <input type="checkbox" :checked="info.done" @change="handleCheck(info.id)" />
      <span v-show="!info.isEdit">{{info.name}}</span>
      <input
        type="text"
        :value="info.name"
        v-show="info.isEdit"
        @blur="handleBlur(info, $event)"
        @keyup.enter="handleBlur(info, $event)"
        ref="input"
      >
    </label>
    <button class="btn btn-danger" @click="handleDelete(info.id)">删除</button>
    <button v-show="!info.isEdit" class="btn btn-edit" @click="handleEdit(info)">编辑</button>
  </li>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
  name: 'ItemView',
  props: ['info'],
  methods: {
    handleCheck(id) {
      // this.onCheck(id)
      this.$bus.$emit('onCheck', id)
    },
    handleDelete(id) {
      // if(confirm('你确定要删除吗？')) {
        // this.onDeleteById(id)
        // this.$bus.$emit('onDeleteById', id)
        pubsub.publish('onDeleteById', id)
      // }
    },
    handleEdit(info) {
      // info.isEdit = true
      // console.log(Object.prototype.hasOwnProperty.call(info, 'isEdit'))
      if (Object.prototype.hasOwnProperty.call(info, 'isEdit')) {
        info.isEdit = true;
      } else {
        this.$set(info, 'isEdit', true)
      }
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    handleBlur(info, e) {
      if (!e.target.value.trim()) {
        return;
        // return alert('输入不能为空');
        // this.$nextTick(() => {
        //   this.$refs.input.focus()
        // })
      }
      info.isEdit = false
      // console.log(this.$refs.input.value)
      this.$bus.$emit('updateTodo', info.id, e.target.value)
    }
  }
}
</script>

<style lang="less" scoped>

/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}
li:hover button {
  display: block;
}

</style>>
